package cn.tsyz.local.common.exception;

import cn.tsyz.local.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.stream.Collectors;

/**
 * 全局异常处理器
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {


    /**
     * 处理业务异常
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<?> handleBusinessException(BusinessException e, HttpServletRequest request) {
        log.warn("业务异常: URI={}, Exception={}", request.getRequestURI(), e.getMessage());
        return Result.error(e.getCode(), e.getMessage());
    }

    /**
     * 处理参数校验异常 (使用@Validated注解)
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException e,
                                                           HttpServletRequest request) {
        BindingResult bindingResult = e.getBindingResult();
        String errorMessage = bindingResult.getFieldErrors().stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.joining("; "));

        log.warn("参数校验异常: URI={}, Exception={}", request.getRequestURI(), errorMessage);
        return Result.error(ErrorCode.PARAM_ERROR, errorMessage);
    }

    /**
     * 处理参数校验异常 (使用@Valid注解)
     */
    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<?> handleBindException(BindException e, HttpServletRequest request) {
        BindingResult bindingResult = e.getBindingResult();
        String errorMessage = bindingResult.getFieldErrors().stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.joining("; "));

        log.warn("参数绑定异常: URI={}, Exception={}", request.getRequestURI(), errorMessage);
        return Result.error(ErrorCode.PARAM_ERROR, errorMessage);
    }

    /**
     * 处理ConstraintViolationException异常 (路径变量校验)
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<?> handleConstraintViolationException(ConstraintViolationException e,
                                                        HttpServletRequest request) {
        String errorMessage = e.getConstraintViolations().stream()
                .map(ConstraintViolation::getMessage)
                .collect(Collectors.joining("; "));

        log.warn("参数约束异常: URI={}, Exception={}", request.getRequestURI(), errorMessage);
        return Result.error(ErrorCode.PARAM_ERROR, errorMessage);
    }

    /**
     * 处理缺少请求参数异常
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<?> handleMissingServletRequestParameterException(
            MissingServletRequestParameterException e, HttpServletRequest request) {

        String errorMessage = "缺少必要参数: " + e.getParameterName();
        log.warn("缺少请求参数: URI={}, Exception={}", request.getRequestURI(), errorMessage);
        return Result.error(ErrorCode.PARAM_IS_NULL, errorMessage);
    }

    /**
     * 处理参数类型不匹配异常
     */
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<?> handleMethodArgumentTypeMismatchException(
            MethodArgumentTypeMismatchException e, HttpServletRequest request) {

        String errorMessage = "参数类型不匹配: " + e.getName() + " 应该为 " + e.getRequiredType().getSimpleName();
        log.warn("参数类型不匹配: URI={}, Exception={}", request.getRequestURI(), errorMessage);
        return Result.error(ErrorCode.PARAM_FORMAT_ERROR, errorMessage);
    }

    /**
     * 处理HTTP消息不可读异常 (如JSON格式错误)
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<?> handleHttpMessageNotReadableException(
            HttpMessageNotReadableException e, HttpServletRequest request) {

        String errorMessage = "请求体格式错误，请检查JSON格式";
        log.warn("请求体格式错误: URI={}, Exception={}", request.getRequestURI(), e.getMessage());
        return Result.error(ErrorCode.PARAM_FORMAT_ERROR, errorMessage);
    }

    /**
     * 处理HTTP请求方法不支持异常
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<?> handleHttpRequestMethodNotSupportedException(
            HttpRequestMethodNotSupportedException e, HttpServletRequest request) {

        String errorMessage = "请求方法不支持: " + e.getMethod() + "，支持的方法: " +
                String.join(",", e.getSupportedMethods());
        log.warn("请求方法不支持: URI={}, Exception={}", request.getRequestURI(), errorMessage);
        return Result.error(ErrorCode.PARAM_ERROR, errorMessage);
    }

    /**
     * 处理空指针异常
     */
    @ExceptionHandler(NullPointerException.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<?> handleNullPointerException(NullPointerException e, HttpServletRequest request) {
        log.error("空指针异常: URI={}", request.getRequestURI(), e);
        return Result.error(ErrorCode.SYSTEM_ERROR, "系统内部错误");
    }

    /**
     * 处理数组越界异常
     */
    @ExceptionHandler(ArrayIndexOutOfBoundsException.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<?> handleArrayIndexOutOfBoundsException(ArrayIndexOutOfBoundsException e,
                                                          HttpServletRequest request) {
        log.error("数组越界异常: URI={}", request.getRequestURI(), e);
        return Result.error(ErrorCode.SYSTEM_ERROR, "系统内部错误");
    }

    /**
     * 处理数字格式异常
     */
    @ExceptionHandler(NumberFormatException.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<?> handleNumberFormatException(NumberFormatException e, HttpServletRequest request) {
        log.warn("数字格式异常: URI={}, Exception={}", request.getRequestURI(), e.getMessage());
        return Result.error(ErrorCode.PARAM_FORMAT_ERROR, "数字格式不正确");
    }

    /**
     * 处理其他未捕获的异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<?> handleException(Exception e, HttpServletRequest request) {
        log.error("系统异常: URI={}", request.getRequestURI(), e);
        return Result.error(ErrorCode.SYSTEM_ERROR, "系统内部错误，请联系管理员");
    }

    /**
     * 处理Throwable
     */
    @ExceptionHandler(Throwable.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<?> handleThrowable(Throwable t, HttpServletRequest request) {
        log.error("严重错误: URI={}", request.getRequestURI(), t);
        return Result.error(ErrorCode.SYSTEM_ERROR, "系统严重错误，请联系管理员");
    }
}
